<!--
 * @Author: quit
 * @Date: 2021-11-23 10:44:34
 * @LastEditTime: 2021-12-09 17:42:55
 * @Descripttion: 类型管理
-->
<template>
  <div id="SubsysManager-container">
    <div class="app-container" style="height: 100%">
      <el-card>
        <el-row>
          <el-button type="primary" size="mini" icon="el-icon-circle-plus-outline" @click="addItemBtn">{{ $t('button.addItems') }}</el-button>
          <el-button type="danger" size="mini" icon="el-icon-delete" @click="deleteSubSysList">{{ $t('button.batchRemove') }}</el-button>
          <el-button type="primary" size="mini" @click="toggleRowExpansion(true)">全部展开</el-button>
          <el-button type="primary" size="mini" @click="toggleRowExpansion(false)">全部折叠</el-button>
        </el-row>
        <el-row>
          <div class="tabel-box">
            <el-table
              ref="dataTreeList"
              v-loading="loading"
              lazy
              :load="tableLoad"
              :data="tableData"
              :max-height="tableHeight"
              row-key="subsystemid"
              :default-expand-all="false"
              :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
              @select="rowSelect"
              @select-all="selectAll"
            >
              <el-table-column type="selection" min-width="40" fixed="left" />
              <el-table-column type="index" label="编号" min-width="55" fixed="left" />
              <el-table-column prop="subsysname" label="类型名" width="240" />
              <el-table-column prop="subsysicon" label="类型icon" width="160" />
              <el-table-column header-align="center" label="icon预览" width="140">
                <template slot-scope="scope">
                  <div v-if="scope.row.subsysicon" class="img-box">
                    <img :src="`${imgBaseURL}/image/icon/${scope.row.subsysicon}/run.gif`">
                  </div>
                </template>
              </el-table-column>
              <el-table-column header-align="center" align="center" prop="sublevel" label="排序号" width="80" />
              <el-table-column header-align="center" align="center" prop="subsysisjg" label="是否结构图" width="100" />
              <el-table-column header-align="center" align="center" prop="submodecontrol" label="是否参与模式控制" width="140" />
              <el-table-column header-align="center" align="center" fixed="right" :label="$t('table.operable')" min-width="220">
                <template slot-scope="scope">
                  <el-button type="primary" size="mini" @click="addHandle(scope.row)">{{ '添加' }}</el-button>
                  <el-button type="success" size="mini" @click="editHandle(scope.row)">{{ $t('button.edit') }}</el-button>
                  <el-button type="danger" size="mini" @click="deleteHandle(scope.row)">{{ $t('button.delete') }}</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-row>
      </el-card>
    </div>
    <!-- 添加弹出层 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogAddVisible" width="30%" @close="dialogAddVisibleClose">
      <el-form ref="dialogFrom" :model="dialogFrom" label-width="100px" class="dialog-from">
        <el-form-item label="类型名">
          <el-input v-model="dialogFrom.subsysname" placeholder="请输入类型名" />
        </el-form-item>
        <el-form-item label="隶属类型">
          <el-select v-model="dialogFrom.subsysparent" clearable filterable placeholder="请选择隶属类型">
            <el-option v-for="(item, index) in parentData" :key="index" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="类型icon" class="icon-select">
          <el-select v-model="dialogFrom.subsysicon" placeholder="请选择类型icon" clearable>
            <el-option v-for="(item, index) in iconData" :key="index" :label="item.label" :value="item.value" />
          </el-select>
          <span class="preview-box">
            <img v-if="dialogFrom.subsysicon" :src="`${imgBaseURL}/image/icon/${dialogFrom.subsysicon}/run.gif`">
            <span v-if="!dialogFrom.subsysicon" class="preview-msg">预览</span>
          </span>
        </el-form-item>
        <el-form-item label="是否结构图">
          <el-select v-model="dialogFrom.subsysisjg" placeholder="请选择项目类型" clearable>
            <el-option v-for="(item, index) in subsysisjgData" :key="index" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="模式控制">
          <el-select v-model="dialogFrom.submodecontrol" placeholder="请选择项目类型" clearable>
            <el-option v-for="(item, index) in submodecontrolData" :key="index" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="类型顺序">
          <el-input v-model="dialogFrom.sublevel" placeholder="请输入图片名称" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogAddVisible = false">取 消</el-button>
        <el-button v-if="dialogAddVisibleState === 0" type="primary" @click="sendAdditem">确 定</el-button>
        <el-button v-if="dialogAddVisibleState === 1" type="primary" @click="sendEditItem">提 交</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import $ from 'jquery'
import { getSubSysInfo, getSubSysName, getIconList, addSubSys, editSubSys, deleteSubSys, deleteSubSysList } from '@/api/BmRequest'
import { mapGetters } from 'vuex'

export default {
  components: {},
  data() {
    return {
      botData: {},
      tableHeight: null,
      loading: false,
      tableData: [],
      isCheckedArr: [],
      dialogTitle: '',
      dialogAddVisible: false,
      dialogAddVisibleState: null,
      dialogFrom: {
        subsysisjg: null,
        subsysicon: null,
        subsysparent: null,
        subtour: null,
        sublevel: null,
        submodecontrol: null,
        subsysname: null
      },
      parentData: [],
      iconData: [],
      subsysisjgData: [
        { label: '无结构图', value: 0 },
        { label: '有结构图', value: 1 }
      ],
      submodecontrolData: [
        { label: '不参与', value: 0 },
        { label: '参与', value: 2 }
      ]
    }
  },
  // 监听属性 类似于data概念
  computed: {
    ...mapGetters(['imgBaseURL'])
  },
  // 监控data中的数据变化
  watch: {},
  created() {
    this.getSubsysInfo()
    this.getSubSysName()
    this.getIconList()
  }, // 生命周期 - 创建完成（可以访问当前this实例）
  mounted() {
    this.setTableHeight()
    window.onresize = () => {
      this.setTableHeight()
    }
  }, // 生命周期 - 挂载完成（可以访问DOM元素）
  beforeCreate() {}, // 生命周期 - 创建之前
  beforeMount() {}, // 生命周期 - 挂载之前
  beforeUpdate() {}, // 生命周期 - 更新之前
  updated() {}, // 生命周期 - 更新之后
  beforeDestroy() {}, // 生命周期 - 销毁之前
  destroyed() {}, // 生命周期 - 销毁完成
  activated() {}, // 如果页面有keep-alive缓存功能，这个函数会触发
  // 方法集合
  methods: {
    // 动态设置表格高
    setTableHeight() {
      var num = $(window).height() - 126
      this.tableHeight = num
    },
    // 获取类型基本数据
    async getSubsysInfo() {
      this.loading = true
      try {
        const { data } = await getSubSysInfo()
        this.tableData = data
      } catch (error) {
        console.log(error)
      } finally {
        this.loading = false
      }
    },
    async getSubSysName() {
      try {
        const { data } = await getSubSysName()
        this.parentData = data
      } catch (error) {
        console.log(error)
      }
    },
    async getIconList() {
      try {
        const { data } = await getIconList()
        this.iconData = data
      } catch (error) {
        console.log(error)
      }
    },

    // 全部展开与折叠
    forArr(arr, isExpand) {
      arr.forEach(i => {
        this.$refs.dataTreeList.toggleRowExpansion(i, isExpand)
        if (i.children) {
          this.forArr(i.children, isExpand)
        }
      })
    },
    toggleRowExpansion(isExpansion) {
      this.forArr(this.tableData, isExpansion)
    },

    /* table选着事件 */
    forCheckedArr(arr, isChecked) {
      arr.forEach(i => {
        this.$refs.dataTreeList.toggleRowSelection(i, isChecked)
        i.isChecked = isChecked
        if (i.isChecked) {
          this.isCheckedArr.push(i.subsystemid)
        } else {
          this.isCheckedArr = this.isCheckedArr.filter(item => {
            return item !== i.subsystemid
          })
        }
        if (i.children) {
          this.forCheckedArr(i.children, isChecked)
        }
      })
    },
    // 当前行选择事件
    rowSelect(selection, row) {
      if (row.children) {
        if (!row.isChecked) {
          this.forCheckedArr(row.children, true)
          row.isChecked = true
          this.isCheckedArr.push(row.subsystemid)
        } else {
          this.forCheckedArr(row.children, false)
          row.isChecked = false
          this.isCheckedArr = this.isCheckedArr.filter(item => {
            return item !== row.subsystemid
          })
        }
      } else {
        if (!row.isChecked) {
          row.isChecked = true
          this.isCheckedArr.push(row.subsystemid)
        } else {
          row.isChecked = false
          this.isCheckedArr = this.isCheckedArr.filter(item => {
            return item !== row.subsystemid
          })
        }
      }
    },
    // 全选事件
    selectAll(selection) {
      this.$refs.dataTreeList.data.map(item => {
        if (item.children) {
          if (!item.isChecked) {
            this.$refs.dataTreeList.toggleRowSelection(item, true)
            this.forCheckedArr(item.children, true)
            item.isChecked = true
            this.isCheckedArr.push(item.subsystemid)
          } else {
            this.$refs.dataTreeList.toggleRowSelection(item, false)
            this.forCheckedArr(item.children, false)
            item.isChecked = false
            this.isCheckedArr = this.isCheckedArr.filter(key => {
              return key !== item.subsystemid
            })
          }
        } else {
          if (!item.isChecked) {
            this.$refs.dataTreeList.toggleRowSelection(item, true)
            item.isChecked = true
            this.isCheckedArr.push(item.subsystemid)
          } else {
            this.$refs.dataTreeList.toggleRowSelection(item, false)
            item.isChecked = false
            this.isCheckedArr = this.isCheckedArr.filter(key => {
              return key !== item.subsystemid
            })
          }
        }
      })
    },

    // 添加按钮
    addItemBtn() {
      this.dialogTitle = '添加类型'
      this.dialogAddVisibleState = 0
      this.dialogAddVisible = true
    },

    // 批量删除
    async deleteSubSysList() {
      if (this.isCheckedArr.length > 0) {
        this.$confirm('此操作将删除所选项目, 是否继续?', '确认操作', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(async() => {
            const { message } = await deleteSubSysList(this.isCheckedArr)
            await this.getSubsysInfo()
            this.$message.success({ message })
            this.isCheckedArr = []
          })
          .catch(error => {
            console.log(error)
            this.$refs.dataTreeList.clearSelection()
            this.isCheckedArr = []
          })
      } else {
        this.$message.warning('请选择需要删除的项目')
      }
    },

    /* 弹出层事件 */
    // 弹出层关闭事件
    dialogAddVisibleClose() {
      this.dialogFrom = {
        subsysisjg: null,
        subsysicon: null,
        subsysparent: null,
        appid: null,
        subtour: null,
        sublevel: null,
        submodecontrol: null,
        subsysname: null
      }
      this.dialogAddVisibleState = null
    },
    // 弹出层确认按钮
    async sendAdditem() {
      try {
        const { message } = await addSubSys(this.dialogFrom)
        this.$message.success(message)
      } catch (error) {
        console.log(error)
        this.$message.error(error)
      } finally {
        this.dialogAddVisible = false
        this.getSubsysInfo()
      }
    },
    // 弹出层提交按钮
    async sendEditItem() {
      try {
        const { message } = await editSubSys(this.dialogFrom)
        this.$message.success(message)
      } catch (error) {
        console.log(error)
        this.$message.error(error)
      } finally {
        this.getSubsysInfo()
        this.dialogAddVisible = false
      }
    },

    /* table-item事件 */
    // 添加当前项的子级数据
    addHandle(data) {
      this.dialogFrom.subsysparent = data.subsystemid
      this.dialogTitle = '添加子级类型数据'
      this.dialogAddVisibleState = 0
      this.dialogAddVisible = true
    },
    // 编辑
    editHandle(data) {
      this.dialogFrom = { ...data }
      this.dialogTitle = '编辑类型'
      this.dialogAddVisibleState = 1
      this.dialogAddVisible = true
    },
    // 删除
    deleteHandle(data) {
      this.$confirm('此操作将删除当前项, 是否继续?', '确认操作', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          const { message } = await deleteSubSys(data.subsystemid)
          await this.getSubsysInfo()
          this.$message.success({ message })
        })
        .catch(error => {
          console.log(error)
        })
    },

    // 懒加载(预留API)
    tableLoad() {}
  }
}
</script>
<style lang="scss" scoped>
#SubsysManager-container {
  .app-container {
    .tabel-box {
      .img-box {
        width: 40px;
        margin: 0 auto;
        img {
          width: 100%;
        }
      }
    }
  }
  .dialog-from {
    .el-form-item {
      margin-bottom: 16px;
    }
    .icon-select {
      position: relative;
      .el-select {
        width: 80%;
      }
      .preview-box {
        position: absolute;
        top: 0;
        display: inline-block;
        margin-left: 15px;
        width: 40px;
        height: 40px;
        overflow: hidden;
        img {
          width: 100%;
          height: 100%;
        }
        .preview-msg {
          color: #c4c7cf;
        }
      }
    }
    .el-input {
      width: calc(100% - 30px);
    }
    .el-select {
      width: calc(100% - 30px);
    }
  }
}
</style>
